import { defineStore } from 'pinia'
import UnauditedCount from '@/components/UnauditedCount.vue'
export const usePermissionStore = defineStore('permission', {
  state: () => ({
    accessRoutes: [],
    permissions: [],
    menus: [],
    routes: [],
  }),
  actions: {
    setPermissions(data) {
      this.permissions = data.permission
      this.routes = data.menu
      this.menus = data.menu
        // .filter((item) => item.menuFlag === 1)
        .map((item) => this.getMenuItem(item))
        .filter((item) => !!item)
        .sort((a, b) => a.sort - b.sort)
    },
    getMenuItem(item, parent) {
      const route = this.generateRoute(item, parent?.key)
      if (route?.path !== '#') this.accessRoutes.push(route)
      // if (!item.show) return null
      const menuItem = {
        label:
          item.code === 'audit'
            ? () => h(UnauditedCount, { title: route.meta.title })
            : route.meta.title,
        key: route.name,
        path: route.path,
        icon: () => h('i', { class: `iconfont ${item.icon} text-16` }),
        order: item.sort ?? 0,
        menuFlag: route.meta.menuFlag,
      }
      const children = item.children || []
      if (children.length) {
        menuItem.children = children
          .map((child) => this.getMenuItem(child, menuItem))
          .filter((item) => !!item)
          .sort((a, b) => a.sort - b.sort)
        if (!menuItem.children.length) delete menuItem.children
      }
      return menuItem?.menuFlag === 1 ? menuItem : null
    },
    generateRoute(item, parentKey) {
      return {
        name: item.code,
        path: item.path,
        // redirect: item.redirect,
        component: item.component,
        meta: {
          icon: item.icon,
          title: item.name,
          // layout: item.layout,
          // keepAlive: !!item.keepAlive,
          parentKey,
          menuFlag: item.menuFlag,
          // btns: item.children
          //   ?.filter((item) => item.type === 'BUTTON')
          //   .map((item) => ({ code: item.code, name: item.name })),
        },
      }
    },
    resetPermission() {
      this.$reset()
    },
    hasPermission(key) {
      return (this.permissions || []).includes(key)
    },
  },
})
